import { Injectable } from '@angular/core';
import { Effect, Actions, ofType } from '@ngrx/effects';
import { of } from 'rxjs/observable/of';
import { catchError, map, switchMap } from 'rxjs/operators';

import { PublicActionTypes, LoadPublicFail, LoadPublicSuccess } from '../actions';
import { ResourceTreeNode } from '../../models';
import { TreeItem } from '../../components';
import { ResourceTreesService } from '../../../../services';

@Injectable()
export class PublicEffects {

    constructor(
        private action$: Actions,
        private restapi: ResourceTreesService
    ) {}

    @Effect()
    loadPublics$ = this.action$
        .pipe(
            ofType(PublicActionTypes.LOAD_PUBLIC),
            switchMap(() => {
                return this.restapi.getTree('public')
                    .pipe(
                        map((publics: ResourceTreeNode[]) => new LoadPublicSuccess(this.toTreeview(publics))),
                        catchError(error => of(new LoadPublicFail(error)))
                    );
            })
        );

    private toTreeview(data: ResourceTreeNode[]): TreeItem[] {
        return data.map((item: ResourceTreeNode) => {
            let node: ResourceTreeNode = { ...item };
            const children: ResourceTreeNode[] = node.children;
            if(children) {
                delete node.children
            }
            return {
                text: item.name,
                value: node,
                disabled: item.disabled || false,
                checked: item.checked || false,
                collapsed: item.collapsed || true,
                children: this.toTreeview(item.children || [])
            };
        });
    }
}